package com.xiaoyu.lanling.feature.moment.data

import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestDefaultHandler
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.event.moment.SubscribeListEvent
import com.xiaoyu.lanling.feature.moment.model.MomentItem

class MomentSubscribeListData : PagedListDataModelWithRequestTag<MomentItem, Any>() {

    val tag = Any()

    override fun doQueryData() {
        RequestCreator.create<SubscribeListEvent>(SubscribeListEvent::class.java)
                .setRequestUrl(HttpConfig.LANLING_MOMENT_SUBSCRIBE_LIST)
                .appendQueryDataTo(listPageInfo)
                .setPostEventWhenFail(true)
                .setRequestHandler(object : RequestDefaultHandler<SubscribeListEvent, JsonData>() {
                    override fun processOriginData(originData: JsonData): SubscribeListEvent {
                        val rawData = originData.optJson("data")
                        val rawList = rawData.optJson("list").toList()
                        val list = mutableListOf<MomentItem>()
                        for(json in rawList){
                            list.add(MomentItem.createSubscribeMoment(json))
                        }
                        updateResult(rawData,list)
                        return SubscribeListEvent(requestTag)
                    }

                    override fun onRequestFinish(data: SubscribeListEvent) {
                        data.post()
                    }
                })
                .enqueue()
    }

    override fun getRequestTag(): Any {
        return tag
    }
}